package com.nj.liandi.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.nj.liandi.common.exception.NoStockException;
import com.nj.liandi.common.to.mq.OrderTo;
import com.nj.liandi.common.to.mq.SeckillOrderTo;
import com.nj.liandi.common.utils.R;
import com.nj.liandi.common.vo.MemberRespVo;
import com.nj.liandi.gulimall.order.OrderCreateTo;
import com.nj.liandi.gulimall.order.constant.OrderConstant;
import com.nj.liandi.gulimall.order.dao.OrderItemDao;
import com.nj.liandi.gulimall.order.entity.OrderItemEntity;
import com.nj.liandi.gulimall.order.entity.PaymentInfoEntity;
import com.nj.liandi.gulimall.order.enume.OrderStatusEnum;
import com.nj.liandi.gulimall.order.feign.CartFeignService;
import com.nj.liandi.gulimall.order.feign.MemberFeignService;
import com.nj.liandi.gulimall.order.feign.ProductFeignService;
import com.nj.liandi.gulimall.order.feign.WareFeignService;
import com.nj.liandi.gulimall.order.interceptor.LoginUserInterceptor;
import com.nj.liandi.gulimall.order.service.OrderItemService;
import com.nj.liandi.gulimall.order.service.PaymentInfoService;
import com.nj.liandi.gulimall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.liandi.common.utils.PageUtils;
import com.nj.liandi.common.utils.Query;

import com.nj.liandi.gulimall.order.dao.OrderDao;
import com.nj.liandi.gulimall.order.entity.OrderEntity;
import com.nj.liandi.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;
    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //获取之前的请求数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //每个线程都要共享之前的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> CartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车所有选中的购物项
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wareFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data!=null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);

        //查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //防重令牌
        String token = UUID.randomUUID().toString().replace("_", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture,CartFuture).get();
        return confirmVo;
    }

//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        String orderToken = vo.getOrderToken();
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0L) {
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //令牌验证成功
            //1.创建订单
            OrderCreateTo order = createTo();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            //金额比对成功
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01) {
                //保存订单
                saveOrder(order);
                //库存锁定
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                R r = wareFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    responseVo.setOrder(order.getOrder());
                    //订单创建成功就发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return responseVo;
                }else {
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                responseVo.setCode(2);
                return responseVo;
            }

        }
    }

    /** description: 返回订单状态
     * version: 1.0 
     * date: 2021/11/4 10:15
     * */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /** description: 定时关闭
     * version: 1.0
     * date: 2021/11/4 14:34
     * */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前这个订单的最新状态
        //加锁
        OrderEntity entity = this.getById(orderEntity.getId());
        if (entity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
           //关闭订单
            entity.setStatus(OrderStatusEnum.CANCLED.getCode());
            boolean b = this.updateById(entity);//加一个乐观锁
            if (b) {
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(orderEntity,orderTo);
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }else {
                //出现订单关闭和支付同时
                throw  new RuntimeException("订单关闭失败");
            }
        }

    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(order.getNote());//备注
        return payVo;
    }

    /** description: 分页查询当前登录的所有的订单信息
     * version: 1.0 
     * date: 2021/11/8 16:07
     * */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(new Query<OrderEntity>().getPage(params), new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId())
                .orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1.保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());//流水号
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());//回调时间
        paymentInfoService.save(infoEntity);
        //2.修改订单状态的信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功状态
            String tradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(tradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Transactional
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //todo 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //todo 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        itemEntity.setRealAmount(multiply);
        //todo 获取当前sku的详细信息进行设置
        itemEntity.setSkuQuantity(seckillOrderTo.getNum());
        orderItemService.save(itemEntity);

    }

    /** description: 保存订单数据
     * version: 1.0
     * date: 2021/11/1 15:36
     * */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    private OrderCreateTo createTo(){
        OrderCreateTo createTo = new OrderCreateTo();
        //1.生成订单号id
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        createTo.setOrderItems(itemEntities);
        //3计算价格和积分相关信息
        computePrice(orderEntity,itemEntities);
        createTo.setOrder(orderEntity);


        return createTo;
    }
    /** description: 计算价格
     * version: 1.0
     * date: 2021/11/1 14:01
     * */
    private void    computePrice(OrderEntity orderEntity,List<OrderItemEntity> itemEntities){
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OrderItemEntity itemEntity : itemEntities) {
            coupon = coupon.add(itemEntity.getCouponAmount());
            intergration = intergration.add(itemEntity.getIntegrationAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            total = total.add(itemEntity.getRealAmount());
            gift = gift.add(new BigDecimal(itemEntity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(itemEntity.getGiftGrowth().toString()));
        }
        //设置订单价格相关信息
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(intergration);
        //设置积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    /*
     * description: 创建订单
     * version: 1.0
     * date: 2021/10/29 17:44
     * author: maizj
     * param: [orderSn]
     * @return void
     * */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        //获取收获信息
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareData = fare.getData(new TypeReference<FareVo>(){});
        //设置收获信息
        orderEntity.setFreightAmount(fareData.getFare());
        orderEntity.setReceiverProvince(fareData.getAddress().getProvince());
        orderEntity.setReceiverCity(fareData.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareData.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareData.getAddress().getName());
        orderEntity.setReceiverPhone(fareData.getAddress().getPhone());
        orderEntity.setReceiverRegion(fareData.getAddress().getRegion());
        orderEntity.setReceiverPostCode(fareData.getAddress().getPostCode());
        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }
    
    /*
     * description: 所有订单项数据
     * version: 1.0 
     * date: 2021/10/29 17:49 
     * author: maizj 
     * param: []
     * @return java.util.List<com.nj.liandi.gulimall.order.entity.OrderItemEntity>
     * */
    public List<OrderItemEntity> buildOrderItems(String orderSn){
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems!=null&&currentUserCartItems.size()>0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartIem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartIem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /*
     * description: 构建某一个订单项数据
     * version: 1.0 
     * date: 2021/10/29 17:41 
     * author: maizj 
     * param: [cartIem]
     * @return com.nj.liandi.gulimall.order.entity.OrderItemEntity
     * */
    private OrderItemEntity buildOrderItem(OrderItemVo cartIem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //订单号
        //商品的spu信息
        Long skuId = cartIem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSkuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //商品的sku信息
        itemEntity.setSkuId(cartIem.getSkuId());
        itemEntity.setSkuName(cartIem.getTitle());
        itemEntity.setSkuPic(cartIem.getImage());
        itemEntity.setSkuPrice(cartIem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartIem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartIem.getCount());
        //优惠信息[不做]
        //积分信息
        itemEntity.setGiftGrowth(cartIem.getPrice().multiply(new BigDecimal(cartIem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartIem.getPrice().multiply(new BigDecimal(cartIem.getCount().toString())).intValue());
        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = origin.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }

}